import React, { Component } from 'react';
import { Button, Spin, Form, Input, Upload, Icon, Select } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import AntdInput from '@/components/AntdInput';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileReader from '@/components/FileReader';
import AntdFormItem from '@/components/AntdFormItem';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import SearchSelect from '@/components/SearchSelect';
import {
  formItemFragement,
  queryDict,
  filterAddFile,
  filterDeteteFile,
  queryPerson,
  formatPrice,
} from '@/utils/common';
import { columnsDriver } from '@/pages/Common/common';
import { allDictList, billStateOnlyReadList } from '@/utils/constans';
import { allDispatchType, allUrl, formate, routeUrl, codes, selectDriverPaperList } from './utils';

const { TextArea } = Input;
const { Option } = Select;

@connect(({ driverPaper, component, loading }) => ({
  driverPaperDetail: driverPaper.driverPaperDetail,
  driverPaperInfo: driverPaper.driverPaperInfo,
  formValues: driverPaper.formValues,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.detail],
}))
@Form.create()
export default class DriverPaperOperate extends Component {
  state = {
    detailId: '',
    selectedRows: [],
    ownCompany: '',
    drivers: [],
    disabled: false,
  };
  fileList = [];
  deleteInfoIds = [];

  componentWillMount() {
    const allDict = [allDictList.papersType, allDictList.currencyType];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      driverPaperDetail,
    } = this.props;
    if (!id) return;
    this.handleStateChange([{ detailId: id }]);
    this.selectDriverPaperDetail(id);
  }

  selectDriverPaperDetail = id => {
    const { dispatch, form } = this.props;
    dispatch({
      type: allDispatchType.detail,
      payload: { id },
      callback: data => {
        this.fileList = data.fileList;
        form.setFieldsValue({ fileTokens: data.fileList });
        this.setState({
          drivers: data.driverId ? [{ id: data.driverId }] : [],
        });
      },
    });
  };

  headerOperate = () => {
    const { detailId, disabled } = this.state;
    return (
      <div>
        {disabled ? (
          <AdButton
            type="primary"
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="编辑"
            code={detailId ? codes.edit : codes.add}
          />
        ) : (
          <Button.Group>
            <AdButton
              text="保存"
              type="primary"
              code={detailId ? codes.edit : codes.add}
              onClick={this.saveInfo}
            />
            {detailId && (
              <AdButton
                onClick={() => {
                  this.setState(preState => ({
                    disabled: !preState.disabled,
                  }));
                }}
                text="取消"
                code={detailId ? codes.edit : codes.add}
              />
            )}
          </Button.Group>
        )}
      </div>
    );
  };

  /**
   * 获取表单内容
   */
  saveInfo = () => {
    const { form, driverPaperDetail } = this.props;
    const { detailId, drivers } = this.state;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      const { effeTime, fileTokens, ...params } = values;
      if (effeTime&&effeTime.length>=0) {
        params.expiryStartTime = moment(effeTime[0]).format(formate);
        params.expiryEndTime = moment(effeTime[1]).format(formate);
      }else{
        params.expiryStartTime=''
        params.expiryEndTime=''
      }
      params.fileTokens = filterAddFile(fileTokens);
      params.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
      if (detailId) params.id = detailId;
      params.driverId = drivers.length > 0 ? drivers[0].id : '';
      this.saveOrSaveInfo(params);
    });
  };

  /**
   * 保存数据
   */
  saveOrSaveInfo = params => {
    const { dispatch, formValues } = this.props;
    dispatch({
      type: allDispatchType.save,
      payload: params,
      callback: data => {
        if (!data) return;
        this.setState(preState => ({
          disabled: !preState.disabled,
        }));
        if (params.id) {
          this.selectDriverPaperDetail(params.id);
        } else {
          this.setTabName({
            id: data,
            isReplaceTab: true,
          });
        }
        selectDriverPaperList({ payload: formValues, props: this.props });
      },
    });
  };

  setTabName = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.setTabsName,
      payload,
      callback: data => {
        if (!data) return;
        router.push(`${routeUrl.edit}/${payload.id}`);
      },
    });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  getValue = values => {
    const ownCompany = values.length > 0 ? values[0].mdsCompanyName : '';
    this.setState({
      drivers: values,
      ownCompany,
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      driverPaperDetail,
      dictObject,
    } = this.props;
    const { detailId, disabled, selectedRows, ownCompany } = this.state;
    const detail = driverPaperDetail[detailId] || {};

    const commonParams = {
      getFieldDecorator,
    };

    const editPageParams = {
      title: detail.papersNo || '新增司机证件',
      headerOperate: this.headerOperate(),
      panelTitle: ['基础信息'],
    };

    const prefixSelector = (name, value) => (
      <AntdFormItem code={name} initialValue={value || 'CNY'} {...commonParams}>
        <Select style={{ width: 90 }} disabled={disabled}>
          {dictObject[allDictList.currencyType] &&
            dictObject[allDictList.currencyType].map(item => (
              <Option key={item.code}>{item.value}</Option>
            ))}
        </Select>
      </AntdFormItem>
    );
    // 单号 状态 司机 所属公司 证件类型 证件编号 有限期

    const formItem = [
      [
        <AntdFormItem
          label="单号"
          code="papersNo"
          initialValue={detail.papersNo || '保存后自动生成'}
          {...commonParams}
        >
          <AntdInput disabled={true} />
        </AntdFormItem>,
        (detail.billStatus || detail.status) && (
          <AntdFormItem
            label="状态"
            code="billStatus"
            initialValue={detail.billStatus || detail.status}
            {...commonParams}
          >
            <AdSelect
              disabled={disabled}
              isExist={true}
              data={billStateOnlyReadList}
              disabled={true}
            />
          </AntdFormItem>
        ),
      ],
      [
        <AntdFormItem
          label="司机"
          code="driverId"
          initialValue={detail.driverId}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <SearchSelect
            multiple={false} // 是否多选
            dataUrl={allUrl.driverList}
            url={allUrl.driverDetail}
            selectedData={this.state.drivers} // 选中值
            columns={columnsDriver} // 表格展示列
            onChange={this.getValue} // 获取选中值
            id="driverPaper_operate_1"
            scrollX={500}
            disabled={disabled || detail.driverId}
          />
        </AntdFormItem>,
        <AntdFormItem
          label="所属公司"
          code="mdsCompanyName"
          initialValue={ownCompany ? ownCompany : detail.mdsCompanyName || undefined}
          // rules={[{ required: true }]}
          {...commonParams}
        >
          <Input placeholder="请输入" disabled={true} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="证件类型"
          code="papersType"
          rules={[{ required: true }]}
          initialValue={detail.papersType || undefined}
          {...commonParams}
        >
          <AdSelect isExist={true} disabled={disabled} data={dictObject[allDictList.papersType]} />
        </AntdFormItem>,
        <AntdFormItem
          label="证件编号"
          code="papersNumber"
          initialValue={detail.papersNumber}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="有效期"
          initialValue={
            detail.expiryStartTime
              ? [moment(detail.expiryStartTime), moment(detail.expiryEndTime)]
              : undefined
          }
          code="effeTime"
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AntdDatePicker mode="range" disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="费用"
          code="feeCost"
          initialValue={detail.feeCost ? formatPrice(detail.feeCost) : ''}
          {...commonParams}
          rules={[{ required: true }]}
        >
          <AntdInput
            mode="money"
            disabled={disabled}
            addonBefore={prefixSelector('currencyType', detail.currencyType)}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="备注"
          code="remarks"
          // rules={[
          //   {
          //     validator: (rule, value, callback) => {
          //       checkStrLength(rule, value, callback, 200, '备注');
          //     },
          //   },
          // ]}
          initialValue={detail.remarks}
          {...commonParams}
        >
          <TextArea rows={4} disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="附件"
          code="fileTokens"
          initialValue={detail.fileList}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <FileReader urlType="tms" disabled={disabled} />
        </AntdFormItem>,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <Spin spinning={detailId ? loading : false}>
          <AntdForm>{formItemFragement(formItem)}</AntdForm>
        </Spin>
      </EditPage>
    );
  }
}
